package com.sgb.kjwl.view.ui.activity.manage

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.text.Html
import android.text.InputType
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteUpdateOrganizationBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity
import com.sgb.kjwl.utils.GlideEngine
import com.sgb.kjwl.utils.ReplaceUtils.getHtml
import com.sgb.alimaplibrary.SelectAddressActivity
import com.sgb.knowledgeshare.view.activity.PlayListActivity
import com.sgb.kjwl.view.widget.manage.MImgGetter
import com.sgb.kjwl.view.widget.manage.WebsiteUtils
import com.sgb.kjwl.viewmodel.manage.WebsiteUpDateOrganizationModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.base.model.entity.VideoBean
import com.swgk.core.util.*
import java.io.File
import java.io.Serializable
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList


class WebsiteUpDateOrganizationActivity : AppActivity() {

    @Inject
    lateinit var mViewModel : WebsiteUpDateOrganizationModel
    private lateinit var mBindind : ActivityWebsiteUpdateOrganizationBinding

    private val RESULT_CODE_SELECT = 100 // 返回

    private val REQUEST_CODE_SELECT = 101 // 请求


    private var avatar = ""

    // 1。新增模式下，暂存本地视频文件路径 2.编辑模式，回显视频播放路径，当执行删除操作时，用来判断用户是否删除已上传的视频，当用户重新提交上传时，执行1操作
    private var localVideoUrl = ""


    private val mOrganizationTypes: ArrayList<PickSelectEntity<*>> = ArrayList()

    private var businessOption: OptionsPickerView<PickSelectEntity<*>>? = null

    companion object{
        const val KEY_DATA = "key_data"
        fun launch(activity : Activity, requestCode : Int){
            val intent = Intent(activity, WebsiteUpDateOrganizationActivity::class.java)
            activity.startActivityForResult(intent, requestCode)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        super.setupActivityComponent(appComponent)
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
            .enterpriseManageModule(EnterpriseManageModule()).build().inject(this)
    }

    override fun initView() {
        super.initView()
        mBindind = DataBindingUtil.setContentView(this, R.layout.activity_website_update_organization)
        mBindind.include.titleView.text = "政府/事业单位信息"
        mBindind.tvUpdate.setOnClickListener(this)
        mBindind.include.ivBack.setOnClickListener(this)
        mBindind.linUploadAvatar.setOnClickListener(this)
        //mBindind.linIndustry.setOnClickListener(this)
        mBindind.linOperatingAddress.setOnClickListener(this)
        mBindind.linVideoUpload.setOnClickListener(this)
        mBindind.tvIntroduction.setOnClickListener(this)
        mBindind.ivDeleteVideo.setOnClickListener(this)

        mBindind.tvConcat.inputType = InputType.TYPE_CLASS_TEXT
        mBindind.tvPhone.inputType = InputType.TYPE_CLASS_PHONE
        mBindind.tvFixedNumber.inputType = InputType.TYPE_CLASS_PHONE
        initLiveData()
    }

    override fun init() {
        super.init()
        //网店编号
        val companyNo = SharedPreferenceUtil.getInstance()
            .getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        mViewModel.getWebsiteInfo(companyNo, 3) // 固定为组织
    }

    @SuppressLint("NonConstantResourceId")
    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.iv_back -> finish()
            R.id.lin_upload_avatar -> pictureSelector(true, 500, 1)
//            R.id.lin_industry -> {
//                if (mOrganizationTypes.isEmpty()){
//                    mViewModel.getOrganizationTypes(this)
//                } else {
//                    showTypes()
//                }
//            }
            R.id.lin_operating_address -> {
                val intent = Intent()
                intent.setClass(this, SelectAddressActivity::class.java)
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址")
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址")
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定")
                if (!TextUtils.isEmpty(mViewModel.entity.get()!!.latitude)) {
                    intent.putExtra(
                        SelectAddressActivity.LATITUDE,
                        java.lang.Double.valueOf(
                            Objects.requireNonNull(mViewModel.entity.get())!!.latitude
                        )
                    )
                    intent.putExtra(
                        SelectAddressActivity.LONGTITUDE,
                        java.lang.Double.valueOf(
                            Objects.requireNonNull(mViewModel.entity.get())!!.longitude
                        )
                    )
                } else {
                    intent.putExtra(SelectAddressActivity.LATITUDE, 34.20843)
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, 108.91962)
                }
                startActivityForResult(intent, 255)
            }

            R.id.lin_video_upload -> videoSelector(1, 336)

            R.id.tv_introduction -> mViewModel.getH5Url(activity, mViewModel.entity.get()!!.introduction,
                "quillEditor",
                REQUEST_CODE_SELECT,
                "政府/单位介绍"
            )

            R.id.tv_update -> if (!ClickUtils.isDoubleClick()) {
                if (isInputValid()) {
                    if (TextUtils.isEmpty(localVideoUrl)) {
                        mViewModel.entity.get()!!.videoUrl = ""
                        mViewModel.entity.get()!!.coverUrl = ""
                        mViewModel.entity.get()!!.video = ""
                    }
                    uploadAvatar()
                }
            }
            R.id.iv_delete_video -> {
                localVideoUrl = ""
                mBindind.linVideoUpload.visibility = View.VISIBLE
                mBindind.rlVideoView.visibility = View.GONE
                mBindind.linLabel.visibility = View.GONE
            }
        }
    }

    private fun isInputValid(): Boolean {
        if (TextUtils.isEmpty(mBindind.tvIndustryName.text.toString().trim())) {
            MToast.showToast(this, "请选择机构类型")
            return false
        }
        if (TextUtils.isEmpty(mBindind.tvConcat.text.toString().trim())) {
            MToast.showToast(this, "请输入联系人")
            return false
        }
        if (TextUtils.isEmpty(mBindind.tvPhone.text.toString().trim())) {
            MToast.showToast(this, "请输入手机号码")
            return false
        }
        if (!CheckUtils.isMobile(mBindind.tvPhone.text.toString().trim())) {
            MToast.showToast(this, "请输入正确的手机号码")
            return false
        }
        if (!TextUtils.isEmpty(mBindind.tvEmail.text.toString().trim()) && !CheckUtils.isEmails(mBindind.tvEmail.text.toString().trim())) {
            MToast.showToast(this, "请输入正确的邮箱号码")
            return false
        }
        if (TextUtils.isEmpty(mBindind.tvOperatingAddress.text.toString().trim())) {
            MToast.showToast(this, "请选择详细地址")
            return false
        }
        if (TextUtils.isEmpty(mBindind.cfkBusinessScope.editContent.trim())) {
            MToast.showToast(this, "请输入经营范围")
            return false
        }
        if (TextUtils.isEmpty(mBindind.cfkPurpose.editContent.trim())){
            MToast.showToast(this, "请输入宗旨和")
            return false
        }
        mViewModel.entity.get()!!.organizers = mBindind.tvOrganizer.text.toString().trim()
        mViewModel.entity.get()!!.contactPerson = mBindind.tvConcat.text.toString().trim()
        mViewModel.entity.get()!!.contactPhone = mBindind.tvPhone.text.toString().trim()
        mViewModel.entity.get()!!.fixedPhone = mBindind.tvFixedNumber.text.toString().trim()
        mViewModel.entity.get()!!.registrationDepartment = mBindind.tvDepartment.text.toString().trim()
        mViewModel.entity.get()!!.email = mBindind.tvEmail.text.toString().trim()
        mViewModel.entity.get()!!.businessScope = mBindind.cfkBusinessScope.editContent.trim()
        mViewModel.entity.get()!!.purpose = mBindind.cfkPurpose.editContent.trim()
        mViewModel.entity.get()!!.businessIds = "" //传空 不然后台报错

        return true
    }

    /*
     * 上传企业简介头像信息
     * */
    private fun uploadAvatar() {
        //过滤已上传头像且上传新头像
        if (!TextUtils.isEmpty(avatar)) {
            if (!TextUtils.isEmpty(avatar)) {
                val file = File(avatar)
                mViewModel.uploadAvatarFileModel(file, 1)
            }
        } else {
            mViewModel.entity.get()!!.logo = ""
            mViewModel.setWebsiteInfo()
        }
    }

    /*
     * 请求上传简介头像信息的结果回调
     * */
    fun uploadAvatarResult(url: String?) {
        avatar = ""
        mViewModel.entity.get()!!.logo = url
        mViewModel.setWebsiteInfo()
    }

    fun initLiveData(){
        mViewModel.message.observe(this, {
            if (!TextUtils.isEmpty(it)){
                MToast.showToast(this, it)
                val intent = Intent()
                intent.putExtra(KEY_DATA, mViewModel.entity.get())
                setResult(RESULT_OK, intent)
                finish()
            }
        })
        mViewModel.websiteInfo.observe(this, {
            if (it != null){
                showWebsiteInfo(it)
            }
        })
        mViewModel.upLoadResult.observe(this, {
            if (!TextUtils.isEmpty(it)){
                uploadAvatarResult(it)
            }
        })
        //机构类型
        mViewModel.mOrganTypes.observe(this, {
            mOrganizationTypes.clear()
            if (it != null) {
                mOrganizationTypes.addAll(it)
                showTypes()
            }
        })


        mViewModel.videoId.observe(this, {
            if (!TextUtils.isEmpty(it)){
                 uploadVideoResult(it)
            }
        })

    }

    fun showWebsiteInfo(entity: WebsiteInfoEntity) {
        mBindind.viewModel = entity
        mViewModel.entity.set(entity)
        setAvatarView(entity.logo)
        mBindind.tvIndustryName.text = entity.institutionalTypeName
        if (!TextUtils.isEmpty(entity.introduction)) {
            val body = getHtml(entity.introduction)
            mBindind.tvIntroduction.text = Html.fromHtml(
                body,
                MImgGetter(activity, mBindind.tvIntroduction),
                null
            )
        }
        if (!TextUtils.isEmpty(entity.videoUrl)) {
            localVideoUrl = entity.videoUrl
            mBindind.linVideoUpload.visibility = View.GONE
            mBindind.rlVideoView.visibility = View.VISIBLE
            mBindind.linLabel.visibility = View.GONE
            mBindind.rlVideoView.setOnClickListener { v ->
                WebsiteUtils.getInstance().openVideo(this, entity.video, entity.videoUrl, entity.coverUrl)
            }
        }
    }

    private fun showTypes() {
        if (mOrganizationTypes.isEmpty()) return
        if (businessOption == null) {
            businessOption = OptionsPickerBuilder(
                this
            ) { options1: Int, options2: Int, options3: Int, v: View? ->
                val content = mOrganizationTypes[options1].projectscale
                mBindind.tvIndustryName.text = content
                mViewModel.entity.get()!!.institutionalTypeName = mOrganizationTypes[options1].projectscale
                mViewModel.entity.get()!!.institutionalTypeNo = mOrganizationTypes[options1].no
            }.setCancelText("取消").setSubCalSize(15)
                .setCancelColor(resources.getColor(R.color.color_tab_two))
                .setTitleText("请选择机构类型")
                .setTitleColor(resources.getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(resources.getColor(R.color.color_main))
                .build<PickSelectEntity<*>>()
        }
        businessOption!!.setPicker(mOrganizationTypes)
        businessOption!!.setSelectOptions(0)
        businessOption!!.show()
    }



    // -----获取视频---------------------------------------------------------------------------
    fun videoSelector(number: Int, requestCode: Int) {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofVideo())
            .imageEngine(GlideEngine.createGlideEngine())
            .selectionMode(PictureConfig.MULTIPLE)
            .isCompress(true) //是否压缩
            .minimumCompressSize(10240) //小于10M不压缩
            .maxSelectNum(number) //判断还能选多少张图片
            .forResult(requestCode)
    }

    /*
     * 请求上传视频返回的数据
     * */
    fun uploadVideoResult(videoId: String?) {
        mViewModel.entity.get()!!.video = videoId
        runOnUiThread {
            if (!TextUtils.isEmpty(localVideoUrl)) {
                mViewModel.entity.get()!!.coverUrl = localVideoUrl
                mViewModel.entity.get()!!.videoUrl = localVideoUrl
                mBindind.linVideoUpload.visibility = View.GONE
                mBindind.rlVideoView.visibility = View.VISIBLE
                mBindind.linLabel.visibility = View.GONE
                mBindind.rlVideoView.setOnClickListener { v ->
                    val videoBeanList: MutableList<VideoBean> = ArrayList()
                    val videoBean = VideoBean()
                    videoBean.videoId = videoId
                    videoBean.coverURL = localVideoUrl
                    videoBean.cover = ""
                    videoBeanList.add(videoBean)
                    val intent = Intent(activity, com.sgb.knowledgeshare.view.activity.PlayListActivity::class.java)
                    intent.putExtra(com.sgb.knowledgeshare.view.activity.PlayListActivity.VIDEOLISTBEAN, videoBeanList as Serializable)
                    intent.putExtra(com.sgb.knowledgeshare.view.activity.PlayListActivity.PSO, 0)
                    intent.putExtra(com.sgb.knowledgeshare.view.activity.PlayListActivity.IS_ShOW_USER, false)
                    intent.putExtra(com.sgb.knowledgeshare.view.activity.PlayListActivity.VIDEOTYPE, "website_video")
                    activity.startActivity(intent)
                }
            }
        }
    }

    /*
     * 设置企业简介头像信息
     * */
    private fun setAvatarView(url: String) {
        if (!TextUtils.isEmpty(url)) {
            val options = RequestOptions()
                .placeholder(R.drawable.icon_organization_default) //图片加载出来前，显示的图片
                .error(R.drawable.icon_organization_default) //图片加载失败后，显示的图片
                .transform(CircleCrop())
            Glide.with(this).load(url).apply(options).into(mBindind.ivShopAvatar)
        }
    }

    override fun onPictureSelectorResult(selectList: List<LocalMedia>) {
        if (selectList != null && selectList.isNotEmpty()) {
            setAvatarView(selectList[0].realPath)
            avatar = selectList[0].realPath
        }
    }

    /*
     * 请求地图地址返回的数据
     * */
    private fun setAddressText(data: Intent) {
        val lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0.0)
        val lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0.0)
        val address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION)
        mViewModel.entity.get()!!.latitude = lat.toString() + ""
        mViewModel.entity.get()!!.longitude = lon.toString() + ""
        mBindind.tvOperatingAddress.text = address
        mViewModel.entity.get()!!.address = address
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SELECT && resultCode == RESULT_CODE_SELECT) { //组织简介返回
            if (data != null) {
                var body = data.getStringExtra("body").trim { it <= ' ' }
                mViewModel.entity.get()!!.introduction = body
                body = getHtml(body)
                mBindind.tvIntroduction.text = Html.fromHtml(
                    body,
                    MImgGetter(activity, mBindind.tvIntroduction),
                    null
                )
            }
        }
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            255 -> {
                if (data == null) return
                setAddressText(data)
            }
            336 -> {
                val selectList1 = PictureSelector.obtainMultipleResult(data)
                localVideoUrl = selectList1[0].realPath
                Glide.with(this)
                    .asBitmap()
                    .load(localVideoUrl)
                    .apply(RequestOptions().placeholder(R.drawable.null_img_list))
                    .into(object : SimpleTarget<Bitmap?>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap?>?
                        ) {
                            mBindind.ivVideoCoverUrl.setImageBitmap(resource)
                        }

                    })
                mViewModel.getVideoParamsSTS(localVideoUrl, this)
            }
        }

    }


}